#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <stdbool.h>

#define MAX_BUFFER_SIZE 1024

void error(const char *msg) {
    perror(msg);
    exit(1);
}

int main(int argc, char *argv[]) {
    if (argc != 5) {
        printf("请指定参数：用户名 密码 目标IP地址 端口号\n");
        return 1;
    }

    const char *username = argv[1];
    const char *password = argv[2];
    const char *targetIP = argv[3];
    const char *port_i = argv[4];
	int port = atoi(port_i);
    //int port = 1234; // 指定要使用的端口号

    int sockfd;
    struct sockaddr_in serv_addr;
    char con_info[MAX_BUFFER_SIZE];
    char buffer[MAX_BUFFER_SIZE];

    // 创建socket
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) {
        error("无法创建套接字");
    }

    memset(&serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(port);
    if (inet_pton(AF_INET, targetIP, &(serv_addr.sin_addr)) <= 0) {
        error("无效的IP地址");
    }

    // 连接服务器
    if (connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
        error("无法连接到服务器");
    }

    // 发送用户名和密码进行认证
    snprintf(con_info, MAX_BUFFER_SIZE, "%s:%s", username, password);
    if (send(sockfd, con_info, strlen(con_info), 0) < 0) {
        error("发送认证信息失败");
    }

    char end_command[] = "quit\n";
    bool send_end_command = false;

    while (1) {
        printf("请输入消息：");
        fgets(buffer, MAX_BUFFER_SIZE, stdin);

        // 检查是否输入结束指令
        if (strcmp(buffer, end_command) == 0) {
            send_end_command = true;
        }

        // 发送消息
        if (send(sockfd, buffer, strlen(buffer), 0) < 0) {
            error("发送消息失败");
        }

        if (send_end_command) {
            break;
        }

        // 接收对方的回复
        memset(buffer, 0, sizeof(buffer));
        if (recv(sockfd, buffer, sizeof(buffer), 0) < 0) {
            error("接收消息失败");
        }

        if (strcmp(buffer, end_command) == 0) {
            //send_end_command = true;
            break;
        }else{
            printf("对方回复：%s", buffer);
        }

        //printf("对方回复：%s", buffer);
    }

    close(sockfd);

    return 0;
}
